<?php

namespace common\components;

/**
 * @author  shuang
 * @date    2016-11-14 22:40:27
 * @version V1.0
 * @desc    
 */
use yii\base\Event;
use common\components\MTools;
use Yii;
use yii\helpers\Json;
use yii\helpers\ArrayHelper;
use frontend\models\WB_Grade;
use yii\db\Query;
use frontend\models\WB_UserProfile;
use frontend\models\WB_UserPayRecord;
use frontend\models\WB_UserOrder;
use frontend\models\WB_GradeRebate;
use frontend\models\WB_User;

class GradeEvent extends Event {

    public $type; //充值 或购买
    public $money;
    public $_gradeid;
    private $_grade;
    public $isupgrade; //是否升级操作

    /*
     * 查询充值升级对象
     */

    protected function moneyGrade() {
        $query = new Query();
        $query->from(WB_Grade::tableName());
        $moneyfield = "upgrade_price";//$this->type === 1 ? "advance_payment" : "upgrade_price";
        $query->where("$moneyfield = (SELECT MAX($moneyfield) from " . WB_Grade::tableName() . " where $moneyfield <=" . $this->money . ")");
        $this->_grade = $query->one();
    }

    /*
     * 检测商户当前级别与升级
     * return boolean true 更新升级  false 不更新升级
     */

    protected function checkUserCurrentGrade() {
        $userid = ArrayHelper::getValue($this->data, "userid",Yii::$app->user->id);
        $user = WB_UserProfile::find()->where("userid=" . $userid)->one();
        $this->moneyGrade();
        if ($user->gradeid < $this->_grade["id"]) {
            $user->gradeid = $this->_grade["id"];
            $user->update();
        }
        return $user;
    }

    /*
     * 返利给推荐人账户
     * @params $invite_code
     * @params $username
     */

    protected function addrebateRecord($invite_code, $username) {
        $res = WB_User::find()->with(["userprofile"])->where("my_code='$invite_code'")->asArray()->one();
        if ($res) {
            //获取返利比例
            $graderebate = WB_GradeRebate::find()->where("gradeid=" . ArrayHelper::getValue($res, "userprofile.gradeid"))->one();
            if ($graderebate instanceof WB_GradeRebate) {
                WB_UserPayRecord::createRecord($res["id"], $this->money * $graderebate->rebate_rate, 1, 5, "获得" . $username . "的充值￥" . $this->money . "返利");
            }
        }
    }

    /*
     * 检测账户余额
     */

    protected function checkAccount() {
        $account = \frontend\models\WB_UserAccount::find()->where("userid=" . Yii::$app->user->id)->one();
        if ($account instanceof $account) {
            return $account;
        }
    }

    /*
     * 更新充值订单
     */

    protected function updateOrder() {
        $res = WB_UserOrder::find()->where("id=:order_no", [":order_no" => ArrayHelper::getValue($this->data, "order_no")])->one();
        if (!$res instanceof WB_UserOrder) {
            $this->sender->message = "订单不存在";
            return false;
        }
        if($res->status == 2){
            $this->render->message = "当前订单已交易成功，请不要重复提交！";
            return false;
        }
        $res->status = 2;
        return $res->update();
    }

    /*
     * 充值升级事件upgrade
     */

    public function upgrade() {
        $trans = Yii::$app->db->beginTransaction();
        try {
            if ($this->updateOrder()) {
                //产生充值记录
                $userid = ArrayHelper::getValue($this->data, "userid",Yii::$app->user->id);
                WB_UserPayRecord::createRecord($userid, $this->money);
                //升级代理级别
                $userprofile = $this->checkUserCurrentGrade();
                //返利给推荐账户
                $this->addrebateRecord($userprofile->invite_code,$userprofile->username);
                $trans->commit();
                $this->sender->flag = true;
            }
        } catch (Exception $ex) {
            $trans->rollbock();
            throw new \yii\web\NotFoundHttpException();
        }
    }

    /*
     * 判断是否允许升级
     */

    public function allowupgrade() {
        $amount = $this->checkAccount();
        if ($amount->amount) {
            $grademodel = WB_Grade::findOne($this->_gradeid);
            if ($this->type === 1) {
                $money = $grademodel->advance_payment;
            } else {
                $money = $grademodel->upgrade_price;
            }
            if ($amount->amount >= $money) {
                $this->sender->flag = true;
            }
        }
        $this->sender->message = "账户余额不足，不能升级到此级别！";
    }

    public function withdrawal() {
        $amount = $this->checkAccount();
        if ($amount->rebate_amount >= MTools::getYiiParams("rebate_drawal")) {
            $this->sender->message = "提现已申请";
        } else {
            $this->sender->message = "您账户的返利金额不足以提现！";
        }
    }

    public function rebateup() {
        $amount = $this->checkAccount();
        if ($amount->rebate_amount > 0) {
            $trans = Yii::$app->db->beginTransaction();
            try {
                //返利充值
                $rebate_amount = $amount->rebate_amount;
                $amount->amount = $amount->amount + $rebate_amount;
                $amount->rebate_amount = 0;
                if ($amount->update()) {
                    //产生充值记录
                    \frontend\models\WB_UserPayRecord::createRecord(Yii::$app->user->id, $rebate_amount, 1, 8);
                    $trans->commit();
                    $this->sender->flag = true;
                    $this->sender->message = "返利充值成功";
                }
            } catch (Exception $ex) {
                $trans->rollbock();
                throw new \yii\web\NotFoundHttpException();
            }
        } else {
            $this->sender->message = "您账户的返利金额是0，无法充值账户！";
        }
    }

}
